package com.sdy.supermarket.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.supermarket.biz.mapper.GsResMapper;
import com.sdy.supermarket.biz.model.GsCategoryManage;
import com.sdy.supermarket.biz.mapper.GsCategoryManageMapper;
import com.sdy.supermarket.biz.model.GsRes;
import com.sdy.supermarket.biz.service.GsCategoryManageService;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import com.sdy.supermarket.biz.utils.TreeUtils;
import com.sdy.supermarket.biz.vo.GsCategoryManageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hyh
 * @since 2019-08-05
 */
@Slf4j
@Service
public class GsCategoryManageServiceImpl extends BaseServiceImpl<GsCategoryManage> implements GsCategoryManageService {
    @Resource
    private GsCategoryManageMapper gsCategoryManageMapper;

    @Resource
    private GsResMapper gsResMapper;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public GsCategoryManage addCategory(Integer aimsId, GsCategoryManage categoryManage) throws BizException {
        if (aimsId == 0) {
            List<GsCategoryManage> gsCategoryManages = gsCategoryManageMapper.selectList(Wrappers.<GsCategoryManage>lambdaQuery().eq(GsCategoryManage::getPid, 0));
            categoryManage.setPid(0);
            categoryManage.setLevel(gsCategoryManages.size() + 1);
            categoryManage.setCreateTime(new Date());
        } else {
            // 获取目标分类信息
            GsCategoryManage aims = gsCategoryManageMapper.selectById(aimsId);
            List<GsCategoryManage> aimsList = gsCategoryManageMapper.selectList(Wrappers.<GsCategoryManage>lambdaQuery().eq(GsCategoryManage::getPid, aims.getId()));
            categoryManage.setPid(aims.getId());
            categoryManage.setLevel(aimsList.size() + 1);
            categoryManage.setCreateTime(new Date());
        }
        int insert = gsCategoryManageMapper.insert(categoryManage);
        Assert.isTrue(insert == 0, "新增失败");
        List<GsCategoryManage> list = gsCategoryManageMapper.selectList(Wrappers.<GsCategoryManage>lambdaQuery().eq(GsCategoryManage::getId, categoryManage.getId()));
        return list.get(0);
    }

    @Override
    public IPage<GsRes> getResList(Integer id, Page<GsRes> page) {
        IPage<GsRes> iPage = gsResMapper.selectPage(page, Wrappers.<GsRes>lambdaQuery().eq(GsRes::getCategory, id).select(GsRes::getId, GsRes::getName, GsRes::getState));
        return iPage;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int updateCategory(GsCategoryManage categoryManage) throws BizException {
        Assert.isNull(categoryManage.getId(), "ID不能为空");
        categoryManage.setPid(null);
        categoryManage.setCreateTime(null);
        categoryManage.setLevel(null);
        int update = gsCategoryManageMapper.updateById(categoryManage);
        return update;
    }

    @Override
    public List<GsCategoryManageVo> getTreeList() {
        List<GsCategoryManageVo> all = gsCategoryManageMapper.getAll();
        List<GsCategoryManageVo> treeList = TreeUtils.toTree(all, "id", "pid", "children", GsCategoryManageVo.class);
        return treeList;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int delById(Integer id) throws BizException {
        Assert.isNull(id, "ID为NULL");
        // 删除前需要判断该分类下是否有应用存在，没有应用存在才能够删除
        List<GsRes> gsRes = gsResMapper.selectList(Wrappers.<GsRes>lambdaQuery().eq(GsRes::getCategory, id).select(GsRes::getName, GsRes::getState));
        Assert.isTrue(gsRes.size() > 0, "被删除的分类下不能够存在应用");
        // 删除之后需要整理受影响的分类level
        GsCategoryManage selectById = gsCategoryManageMapper.selectById(id);
        Assert.isNull(selectById, "目标对象为空");
        List<GsCategoryManage> updateList = gsCategoryManageMapper.selectList(Wrappers.<GsCategoryManage>lambdaQuery().eq(GsCategoryManage::getPid, selectById.getPid())
                .gt(GsCategoryManage::getLevel, selectById.getLevel()));
        updateList.forEach(gs -> gs.setLevel(gs.getLevel() - 1));
        int batchUpdateStatus = updateList.size() == 0 ? 1 : 0;
        if (updateList.size() > 0) batchUpdateStatus = gsCategoryManageMapper.batchUpdate(updateList);
        int deleteById = gsCategoryManageMapper.deleteById(id);
        if (batchUpdateStatus == 0 || deleteById == 0) throw new BizException("删除失败");
        return 1;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int changeResCategory(Integer resId, Integer categoryId) {
        GsRes res = new GsRes().setId(resId).setCategory(categoryId);
        int update = gsResMapper.updateById(res);
        return update;
    }
}
